<?php

namespace app\admin\service;

use app\admin\dao\TradeDao;
use app\admin\model\UM as UM;
use app\admin\service\traits\TuTrait;
use app\admin\traits\StatisticsTrait;
use app\common\model\Account;
use app\common\model\AccountUser;
use app\common\model\Consulting;
use app\common\model\ConsultingServer;
use app\common\model\LawCase;
use app\common\model\Trade;
use ShidianUtil\Utils\TimeUtil;
use think\facade\Db;

/**
 * Class OrderStatisticsService
 * @package app\admin\service
 */
class OrderStatisticsService
{
    use TuTrait;
    use StatisticsTrait;

    // dao
    private TradeDao $tradeDao;

    public function __construct(TradeDao $tradeDao)
    {
        $this->tradeDao = $tradeDao;
    }

    /**
     * 数据页面-订单统计
     * @param array $params
     * @return array
     */
    public function readOfData(array $params): array
    {
        $now = time();

        $params['startTime'] ??= $now;
        // $startTime = TimeUtil::stamp(TimeUtil::DAY, $params['startTime'])
        $startTime = $params['startTime'];

        $params['endTime'] ??= $now;
        // $endTime = TimeUtil::stamp(TimeUtil::DAY, $params['endTime'], false);
        $endTime = $params['endTime'];
        if (is_numeric($endTime)) {
            $endTime = TimeUtil::stamp(TimeUtil::DAY, $endTime, false);
        }

        return [
            'datas' => $this->readDatas($startTime, $endTime),
            'tu' => $this->readTu($startTime, $endTime),
        ];
    }

    private function readDatas($startTime, $endTime): array
    {
        // 提问人数
        $value = $this->questionMemberNum($startTime, $endTime);
        $server = ConsultingServer::where('deleted', '0')
            ->where("serverType", 2)
            ->append(['dataIconImg'])
            ->find();
        $data = [
            [
                'name' => '提问人数',
                'dataIconImg' => $server ? $server->dataIconImg : '',
                'value' => $value,
            ]
        ];
        // // 免费咨询（提问总数）
        // $consultingServer = ConsultingServer::getTable();
        // $data = ConsultingServer::where('deleted', '0')
        //     ->where("$consultingServer.serverType", 2)
        //     ->tableField(['name', 'dataIcon'], $consultingServer)
        //     ->append(['dataIconImg'])
        //     ->orderValues("$consultingServer.serverType", [2, 6, 3, 4, 5, 1])
        //     ->order("$consultingServer.ord", 'ASC')
        //     ->order("$consultingServer.id", 'DESC')
        //     ->select()
        //     ->toArray();
        // if (!empty($data)) {
        //     $data[0]['value'] = $value;
        // }

        // 付费咨询（人数）
        $consulting = Consulting::getTable();
        $consultingServer = ConsultingServer::getTable();
        $subSql = "SELECT consultingServerId, count(distinct memberId) AS `value` FROM `$consulting` WHERE created >= $startTime AND created <= $endTime AND status >= 1 GROUP BY consultingServerId";
        $data1 = ConsultingServer::leftJoin("($subSql) tmp", "$consultingServer.id=tmp.consultingServerId")
            ->tableField(['name', 'dataIcon'], $consultingServer)
            ->tableField(['value'], 'tmp')
            ->where('deleted', '0')
            ->where("$consultingServer.serverType", '<>', 2)
            ->withAttr([
                'value' => fn($value) => $value ?: 0,
            ])
            ->append(['dataIconImg'])
            ->orderValues("$consultingServer.serverType", [2, 6, 3, 4, 5, 1])
            ->order("$consultingServer.ord", 'ASC')
            ->order("$consultingServer.id", 'DESC')
            ->select()
            ->toArray();

        // 合并
        $data = array_merge($data, $data1);

        // 后面的

        // 悬赏数
        $rewardCount = Trade::timeRange($startTime, $endTime, 'created', 'created')
            ->where('payStatus', Trade::PAID)
            ->consultingTrade()
            ->where('tradeType', TRADE_REWARD)
            ->group('memberId')
            ->count();

        // 新增案源
        $lawCaseCount = LawCase::timeRange($startTime, $endTime, 'created', 'created')
            ->group('memberId')
            ->count();

        // 支付总数
        $payCount = Trade::timeRange($startTime, $endTime, 'created', 'created')
            ->where('payStatus', Trade::PAID)
            ->consultingTrade()
            ->group('memberId')
            ->count();

        // 支付总额
        $paySum = Trade::timeRange($startTime, $endTime, 'created', 'created')
            ->where('payStatus', Trade::PAID)
            ->consultingTrade()
            ->sum('payMoney');

        // 获客卡存量
        $memberCardSum = Account::where('payMethod', PAYMENT_CARD)
            ->where('memberId', '<>', '1')
            ->sum('balance');
        $userCardSum = AccountUser::where('payMethod', PAYMENT_CARD)
            ->sum('balance');
        $memberCardSum = is_numeric($memberCardSum) ? $memberCardSum : 0;
        $userCardSum = is_numeric($userCardSum) ? $userCardSum : 0;
        $cardSum = $memberCardSum + $userCardSum;

        // 补贴金额
        // $subsidySum = ConsultingSubsidy::where('settleStatus', 'SETTLED')->sum('subsidy');

        // 补贴数
        // $subsidyCount = ConsultingSubsidy::where('settleStatus', 'SETTLED')
        //     ->group('settleLawyerId')
        //     ->count();

        $other = [
            ['dataIconImg' => image_url('/storage/static/images/data/xs.png', 'min'), 'name' => '悬赏数', 'value' => $rewardCount,],
            ['dataIconImg' => image_url('/storage/static/images/data/14.png', 'min'), 'name' => '新增案源', 'value' => $lawCaseCount,],
            ['dataIconImg' => image_url('/storage/static/images/data/17.png', 'min'), 'name' => '支付总数', 'value' => $payCount,],
            ['dataIconImg' => image_url('/storage/static/images/data/16.png', 'min'), 'name' => '支付总额', 'value' => $paySum,],
            ['dataIconImg' => image_url('/storage/static/images/caiwu/butiejine.png', 'min'), 'name' => '获客卡存量', 'value' => $cardSum,],
            // ['dataIconImg' => image_url('/storage/static/images/caiwu/butiejine.png', 'min'), 'name' => '补贴总金额', 'value' => $subsidySum,],
            // ['dataIconImg' => image_url('/storage/static/images/caiwu/butieshu.png', 'min'), 'name' => '补贴总数', 'value' => $subsidyCount,],
        ];

        return array_merge($data, $other);
    }

    private function readTu($startTime, $endTime): array
    {
        $min = 7 * 86400 - 1;
        if ($endTime - $startTime < $min) {
            $startTime = $endTime - $min;
        }

        $times = $this->getTimes($startTime, $endTime);

        // 提问人数
        $consulting = Consulting::getTable();
        // $sql = "SELECT from_unixtime(created,'%Y-%m-%d') AS `date`, count(*) AS `value` FROM `$consulting` WHERE created >= :startTime AND created <= :endTime AND status >= 1 GROUP BY `date`, ";
        $sql = "SELECT `date`, count(*) AS `value` FROM ( SELECT from_unixtime(created,'%Y-%m-%d') AS `date`, `memberId` FROM `$consulting` WHERE created >= :startTime AND created <= :endTime AND status >= 1 GROUP BY `date`, `memberId` ) tmp GROUP BY `date`";
        $consultings = Db::query($sql, ['startTime' => $startTime, 'endTime' => $endTime]);
        $consultings = array_column($consultings, 'value', 'date');
        $consultings = $this->wrapTuItem($times, $consultings);

        // 案源数
        $lawCase = LawCase::getTable();
        $sql = "SELECT from_unixtime(created,'%Y-%m-%d') AS `date`, count(*) AS `value` FROM `$lawCase` WHERE created >= :startTime AND created <= :endTime GROUP BY `date`";
        $lawCases = Db::query($sql, ['startTime' => $startTime, 'endTime' => $endTime]);
        $lawCases = array_column($lawCases, 'value', 'date');
        $lawCases = $this->wrapTuItem($times, $lawCases);

        // // 支付总数
        $trade = Trade::getTable();
        $sql = "SELECT from_unixtime(created,'%Y-%m-%d') AS `date`, count(*) AS `value` FROM `$trade` WHERE created >= :startTime AND created <= :endTime AND payStatus = :payStatus GROUP BY `date`";
        $pay = Db::query($sql, ['startTime' => $startTime, 'endTime' => $endTime, 'payStatus' => Trade::PAID]);
        $pay = array_column($pay, 'value', 'date');
        $pay = $this->wrapTuItem($times, $pay);

        // return [
        //     'data' => [
        //         ['name' => '免费咨询', 'data' => [120, 132, 101, 134, 90, 230, mt_rand(100, 999)], 'color' => '#EBC312',],
        //         ['name' => '案源数', 'data' => [220, 182, 191, 234, 290, 330, mt_rand(100, 999)], 'color' => '#F88135',],
        //         ['name' => '支付总数', 'data' => [150, 232, 201, 154, 190, 330, mt_rand(100, 999)], 'color' => '#438AFF',],
        //     ],
        //     'x' => ['12/04', '12/05', '12/06', '12/07', '12/08', '12/09', '12/10',]
        // ];

        return [
            'data' => [
                ['name' => '提问人数', 'data' => $consultings, 'color' => '#F88135'],
                ['name' => '案源数', 'data' => $lawCases, 'color' => '#EBC312'],
                ['name' => '支付总数', 'data' => $pay, 'color' => '#3970EF'],
            ],
            'x' => $this->getX($times),
        ];
    }

    /**
     * 订单页面-统计
     * @param UM|null $user
     * @param $memberId
     * @param $provinceId
     * @param $cityId
     * @param $payMethod
     * @param $categoryId
     * @param $serverId
     * @param $status
     * @param $startTime
     * @param $endTime
     * @param $kw
     * @return array
     */
    public function readOfOrder(?UM $user, $memberId, $provinceId, $cityId, $payMethod, $categoryId, $serverId, $status, $startTime, $endTime, $kw): array
    {
        if (is_numeric($endTime)) {
            $endTime = TimeUtil::stamp(TimeUtil::DAY, $endTime, false);
        }
        return $this->tradeDao->statisticsListTrades($memberId, $provinceId, $cityId, $payMethod, $categoryId, $serverId, $status, $startTime, $endTime, $kw);
    }
}
